package dao;

import entity.Department;
import entity.Teacher;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

public class TeacherDao implements TeacherDaoInterface {
    private static TeacherDao instance = new TeacherDao();
    private static Collection<Teacher>teachers;

    private TeacherDao() {
    }

    public static TeacherDao getInstance() {
        return instance;
    }

    public Collection<Teacher> findAll(Connection connection, List<Condition> conditionList, Pagination pagination) throws SQLException {
        Collection<Teacher> desiredTeachers = new HashSet<>();
        StringBuilder sql_select = new StringBuilder("SELECT * FROM teacher ");
        if (conditionList != null) {
            String whereClause = Condition.toWhereClause(conditionList);
            sql_select.append(whereClause);
        }
        int totalNum = CommonDao.getInstance().count(connection, "Teacher", conditionList);
        String paginationClause = pagination.toLimitClause(totalNum);
        sql_select.append(paginationClause);
        PreparedStatement pstmt_select = connection.prepareStatement(sql_select.toString());
        ResultSet resultSet_select = pstmt_select.executeQuery();
        while (resultSet_select.next()) {
            Long id = resultSet_select.getLong("id");
            String name = resultSet_select.getString("name");
            int departmentId = resultSet_select.getInt("department_id");
            Department department = DepartmentDaoImpl.getInstance().find(Long.valueOf(departmentId));
            Teacher desiredTeacher = new Teacher(id, name, department);
            desiredTeachers.add(desiredTeacher);
        }
        JdbcHelper.close(resultSet_select, pstmt_select);
        return desiredTeachers;
    }
}